package com.orangelife.mobile.housepurchasing.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.curry.android.adapter.FatherAdapter;
import com.curry.android.http.VolleyHttpUtil;

import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.PullRefreshBaseActivity;

import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.housepurchasing.adapter.HouseLisLeftAdapter;
import com.orangelife.mobile.housepurchasing.adapter.HouseListRightAdapter;
import com.orangelife.mobile.housepurchasing.biz.HouseListHttpBiz;

import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by HeYuCan on 2016/5/18.
 */
public class HouseShowingListActivity extends PullRefreshBaseActivity implements AdapterView.OnItemClickListener {

    @Bind(R.id.iv_title_back)
    ImageView ivBack;
    /** 标题栏的'我要委托' */
    @Bind(R.id.tv_title_entrust)
    TextView tvEntrust;
    @Bind(R.id.rlSelectCity)
    RelativeLayout rlSelectCity;
    /** 选择城市 */
    @Bind(R.id.tv_city)
    TextView tvCity;
    @Bind(R.id.rlSelectNeighbourhood)
    RelativeLayout rlSelectNeighbourhood;
    /** 选择小区,如融侨水乡一期 */
    @Bind(R.id.tv_neighbourhood)
    TextView tvNeighbourhood;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.pf_emptyLayout)
    EmptyLayout pfemptyLayout;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.leftView)
    ListView leftView;
    @Bind(R.id.rightView)
    ListView rightView;
    @Bind(R.id.swipe_ly)
    SwipeRefreshLayout swipeRefreshLayout;

    private HouseLisLeftAdapter<List<Map<String, Object>>> leftAdapter;
    private HouseListRightAdapter<List<Map<String, Object>>> rightAdapter;
    private List<List<Map<String, Object>>> data = new ArrayList<>();
    private Map<String, String> map = new HashMap<>();
    private String saleTypeID = null;
    private String city;
    private String commName;
    private String commID;
    private static final String TAG = "TAG";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_showing_list);
        ButterKnife.bind(this);
        setListViewAdapter();
        initView();
        showProgress();
        requestLeftList(commID);
    }

    private void initView() {
        city = CommSp2.getCityName();
        commName = CommSp2.getCommName();
        commID = CommSp2.getCommID();
        tvCity.setText(city);
        tvNeighbourhood.setText(commName);
        tvEntrust.setOnClickListener(listener);
        rlSelectCity.setOnClickListener(listener);
        rlSelectNeighbourhood.setOnClickListener(listener);
        swipeRefreshLayout.setOnRefreshListener(onRefreshListener);
        swipeRefreshLayout.setColorSchemeColors(R.color.common_blue);
    }

    private SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            requestLeftList(commID);
        }
    };


    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                case R.id.tv_title_entrust:
                    intent.putExtra("commID",commID);
                    intent.setClass(HouseShowingListActivity.this, ToEntrustActivity.class);
                    startActivityForResult(intent, 1);
                    break;
                case R.id.rlSelectCity:
                    intent.putExtra("city", "");
                    intent.setClass(HouseShowingListActivity.this, SelectCityActivity.class);
                    startActivityForResult(intent, 0);
                    break;
                case R.id.rlSelectNeighbourhood:
                    intent.putExtra("city", city);
                    intent.setClass(HouseShowingListActivity.this, SelectCityActivity.class);
                    startActivityForResult(intent, 0);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected EmptyLayout getEmptyLayout() {
        return emptyLayout;
    }

    protected EmptyLayout getEmptyLayoutPf() {
        return pfemptyLayout;
    }

    @Override
    protected List getData() {
        return data;
    }

    @Override
    protected int getDataCount() {
        if (data == null) {
            return 0;
        }
        return data.size();
    }

    @OnClick({R.id.tv_title_entrust, R.id.iv_title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_title_entrust:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("commID", String.valueOf(commID));
                intent.setClass(HouseShowingListActivity.this, ToEntrustActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.iv_title_back:
                finish();
                break;
        }
    }

    /**
     * 加载左侧的房屋销售类型列表
     */
    protected void requestLeftList(String commID) {
        HouseListHttpBiz.requestSaleTypeList(commID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                if (errCode == 1011) {
                    getEmptyLayout().setErrorType(EmptyLayout.NETWORK_ERROR);
                } else if (errCode == 00) {
                    String str = response.toString();
                    listLeft = HouseListHttpBiz.getLeftListRight(str);
                    if (listLeft == null || listLeft.size() == 0) {
                        getEmptyLayout().setErrorType(EmptyLayout.NODATA);
                        getEmptyLayout().setErrorMessage("该小区暂无房源信息!");
                        swipeRefreshLayout.setRefreshing(false);
                        return;
                    }
                    updateListView(listLeft, leftAdapter);
                    Map<String, String> map = (Map<String, String>) listLeft.get(0);

                    saleTypeID = String.valueOf(map.get("saleType"));
                    getEmptyLayoutPf().setVisibility(View.VISIBLE);
                    requestRightList(saleTypeID);
                    leftAdapter.setColorItem(0);
                    swipeRefreshLayout.setVisibility(View.GONE);
                    dismissEmptyLayout();

                } else {
                    dismissEmptyLayout();
                    ToastHelper.getInstance()._toast(
                            "网络不稳定");
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * 加载右侧的房源list
     */
    protected void requestRightList(String saleTypeID) {
        HouseListHttpBiz.requestHouseList(saleTypeID, commID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                if (errCode == 1011) {
                    dismissEmptyLayout();
                    getEmptyLayoutPf().setErrorType(EmptyLayout.NODATA);
                } else if (errCode == 00) {
                    String str = response.toString();

                    listRight = HouseListHttpBiz.getHouseListRight(str);

                    updateListView(listRight, rightAdapter);
                    dismissEmptyLayout();
                    getEmptyLayoutPf().dismiss();
                } else {
                    dismissEmptyLayout();
                    getEmptyLayoutPf().setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            }
        });
    }

    @Override
    protected void requestWhenPullRefresh() {

    }


    List listLeft = null;
    List listRight = new ArrayList();
    private final int WHAT_LIST = 1;
    public static final int WHAT_NO_NET = -2;

    private void dismissEmptyLayout() {
        if (getEmptyLayout() != null) {
            getEmptyLayout().dismiss();
        }
    }


    private void updateListView(List list, FatherAdapter adapter) {
        List refreshList = new ArrayList();

        if (list != null && list.size() > 0) {
            refreshList.addAll(list);
        }
        if (adapter != null) {
            adapter.setList(refreshList);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        switch (parent.getId()) {
            case R.id.leftView:
                onItemClickLeft(view, position);
                break;

            default:
                break;
        }
    }


    /**
     * 绑定和注册listview的adapter和点击事件监听
     */
    private void setListViewAdapter() {

        leftAdapter = new HouseLisLeftAdapter<>(this, data);
        rightAdapter = new HouseListRightAdapter<>(this, data);
        leftView.setAdapter(leftAdapter);
        leftView.setOnItemClickListener(HouseShowingListActivity.this);
        rightView.setAdapter(rightAdapter);

    }

    /**
     * 点击左边选着右边
     *
     * @param view
     * @param position
     */

    private void onItemClickLeft(View view, int position) {

        map = (Map<String, String>) listLeft.get(position);
        leftAdapter.setColorItem(position);
        saleTypeID = String.valueOf(map.get("saleType"));
        getEmptyLayoutPf().setVisibility(View.VISIBLE);
        requestRightList(saleTypeID);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (data != null) {
                city = data.getStringExtra("cityName");
            }
        }
        if (requestCode == 0) {
            if (data != null) {
                city = data.getStringExtra("cityName");
                tvCity.setText(city);
                tvNeighbourhood.setText(data.getStringExtra("commName"));
                commID = data.getStringExtra("commID");
                getEmptyLayout().setVisibility(View.VISIBLE);
                swipeRefreshLayout.setVisibility(View.VISIBLE);
                requestLeftList(commID);
            }
        }

    }

}
